const radius = 1 // 半径
const zMin = 0 // 最小z
// 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
function getParametricEquation(
  startRatio,
  endRatio,
  innerRadiusRatio,
  outerRadiusRatio,
  height,
  isSelected,
  isHovered
) {
  let midRatio = (startRatio + endRatio) / 2

  let startRadian = startRatio * Math.PI * 2
  let endRadian = endRatio * Math.PI * 2
  let midRadian = midRatio * Math.PI * 2

  // 如果只有一个扇形，则不实现选中效果。
  if (startRatio === 0 && endRatio === 1) {
    isSelected = false
  }

  // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
  let offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0
  let offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0

  // 计算高亮效果的放大比例（未高亮，则比例为 1）
  let hoverRate = isHovered ? 1.1 : 1

  // 返回曲面参数方程
  return {
    u: {
      min: -Math.PI,
      max: Math.PI * 3,
      step: Math.PI / 32
    },

    v: {
      min: 0,
      max: Math.PI * 2,
      step: Math.PI / 20
    },

    x: function (u, v) {
      const r = (Math.cos(v) > 0 ? innerRadiusRatio : outerRadiusRatio) * radius

      if (u < startRadian) {
        return offsetX + Math.cos(startRadian) * r * hoverRate
      }
      if (u > endRadian) {
        return offsetX + Math.cos(endRadian) * r * hoverRate
      }
      return offsetX + Math.cos(u) * r * hoverRate
    },

    y: function (u, v) {
      const r = (Math.cos(v) > 0 ? innerRadiusRatio : outerRadiusRatio) * radius

      if (u < startRadian) {
        return offsetY + Math.sin(startRadian) * r * hoverRate
      }
      if (u > endRadian) {
        return offsetY + Math.sin(endRadian) * r * hoverRate
      }
      return offsetY + Math.sin(u) * r * hoverRate
    },

    z: function (u, v) {
      if (u < -Math.PI / 2) {
        return Math.max(Math.cos(u) * height, zMin)
      }
      if (u > (Math.PI * 5) / 2) {
        return Math.max(Math.cos(u) * height, zMin)
      }
      return Math.sin(v) > 0 ? height : zMin
    }
  }
}

// 生成模拟 3D 饼图的配置项
/**
 *
 * @param {Array} pieData
 * @param {String} innerRadius - 内径百分比
 * @param {String} outerRadius - 外径百分比
 * @returns
 */
export function getPie3D(pieData, innerRadius, outerRadius, lableShow) {
  innerRadius = Number.parseFloat(innerRadius)
  outerRadius = Number.parseFloat(outerRadius)

  const innerRadiusRatio = innerRadius / 100
  const outerRadiusRatio = outerRadius / 100

  let total = pieData.reduce((total, item) => (total += item.value), 0)

  pieData.forEach((item) => (item.perValue = item.value / total))

  let series = []
  let sumValue = 0
  let startValue = 0
  let endValue = 0
  let legendData = []
  let linesSeries = [] // line3D模拟label指示线

  // 为每一个饼图数据，生成一个 series-surface 配置
  for (let i = 0; i < pieData.length; i++) {
    sumValue += pieData[i].perValue

    let seriesItem = {
      name: typeof pieData[i].name === 'undefined' ? `series${i}` : pieData[i].name,
      type: 'surface',
      parametric: true,
      shading: 'realistic',
      wireframe: {
        show: false
      },
      realisticMaterial: {
        roughness: 0.7,
        metalness: 0,
        textureTiling: [200, 20]
      },
      pieData: pieData[i],
      pieStatus: {
        selected: false,
        hovered: false
      }
    }

    if (typeof pieData[i].itemStyle != 'undefined') {
      let itemStyle = {}

      typeof pieData[i].itemStyle.color != 'undefined'
        ? (itemStyle.color = pieData[i].itemStyle.color)
        : null
      typeof pieData[i].itemStyle.opacity != 'undefined'
        ? (itemStyle.opacity = pieData[i].itemStyle.opacity)
        : null

      seriesItem.itemStyle = itemStyle
    }
    series.push(seriesItem)
  }
  // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
  // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
  for (let i = 0; i < series.length; i++) {
    endValue = startValue + series[i].pieData.perValue
    series[i].pieData.startRatio = startValue / sumValue
    series[i].pieData.endRatio = endValue / sumValue
    series[i].parametricEquation = getParametricEquation(
      series[i].pieData.startRatio,
      series[i].pieData.endRatio,
      innerRadiusRatio,
      outerRadiusRatio,
      series[i].pieData.perValue,
      series[i].pieData.selected,
      series[i].pieData.hovered
    )
    startValue = endValue

    // 计算label指示线的起始和终点位置
    let midRadian = (series[i].pieData.endRatio + series[i].pieData.startRatio) * Math.PI
    let posX = Math.cos(midRadian) * (1 + Math.cos(Math.PI / 2)) * outerRadiusRatio
    let posY = Math.sin(midRadian) * (1 + Math.cos(Math.PI / 2)) * outerRadiusRatio
    let posZ = Math.log(Math.abs(series[i].pieData.perValue + 1)) * 0.1
    let color = pieData[i].itemStyle.color
    const length = 0.3
    const length2 = 0.1

    let turningPosArr = [posX * (1 + length), posY * (1 + length), posZ * 2]
    let endPosArr = [posX * (1 + length + length2), posY * (1 + length + length2), posZ * 6]

    linesSeries.push(
      {
        type: 'line3D',
        lineStyle: {
          color: color
        },
        data: [[posX, posY, posZ], turningPosArr, endPosArr]
      },
      {
        type: 'scatter3D',
        label: {
          show: true,
          distance: 0,
          position: 'center',
          textStyle: {
            color: '#ffffff',
            backgroundColor: color,
            borderWidth: 1,
            fontSize: 14,
            padding: 5,
            borderRadius: 4
          },
          formatter: '{b}'
        },
        symbolSize: 0,
        data: [{ name: series[i].name + '\n' + series[i].pieData.value, value: endPosArr }]
      }
    )
    legendData.push(series[i].name)
  }

  if (lableShow) series = series.concat(linesSeries)

  // 最底下圆盘
  series.push({
    type: 'surface',
    parametric: true,
    shading: 'realistic',
    silent: false,
    wireframe: {
      show: false
    },
    realisticMaterial: {
      roughness: 0.7,
      metalness: 0,
      textureTiling: [200, 20]
    },
    itemStyle: {
      opacity: 1,
      color: 'rgba(50, 100, 200, 0.3)'
    },
    parametricEquation: {
      u: {
        min: 0,
        max: Math.PI * 2,
        step: Math.PI / 32
      },
      v: {
        min: 0,
        max: Math.PI,
        step: Math.PI / 20
      },
      x: function (u, v) {
        return ((Math.sin(v) * Math.sin(u) + Math.sin(u)) / Math.PI) * 1.5
      },
      y: function (u, v) {
        return ((Math.sin(v) * Math.cos(u) + Math.cos(u)) / Math.PI) * 1.5
      },
      z: function (u, v) {
        return Math.cos(v) > 0 ? zMin - 0.01 : -0.1
      }
    }
  })

  let option = {
    tooltip: {
      textStyle: {
        color: 'var(--ec-text-color)'
      },
      backgroundColor: 'var(--ec-background-color)',
      borderColor: 'var(--ec-border-color)',
      formatter: (params) => {
        const { seriesName, seriesIndex, color } = params

        let total = 0
        let obj = pieData[seriesIndex]

        if (!obj) return

        let target = obj.value
        for (let i = 0; i < pieData.length; i++) {
          total += Number(pieData[i].value)
        }

        return `
        <span style="color: ${color}">${seriesName}</span>
        <b>${obj.value}</b>
        <small>${((target / total) * 100).toFixed(0)}%</small>`
      }
    },
    xAxis3D: {
      min: -radius,
      max: radius
    },
    yAxis3D: {
      min: -radius,
      max: radius
    },
    zAxis3D: {
      min: zMin,
      max: 1
    },
    grid3D: {
      show: false,
      viewControl: {
        autoRotate: true, // 自动旋转
        maxDistance: 100
      },
      boxHeight: 30,
      boxWidth: outerRadius,
      boxDepth: outerRadius,
      light: {
        main: {
          intensity: 1,
          shadow: true
        }
      }
    },
    series: series
  }
  return option
}
